import { ScoringRule } from "@/domain/ScoringRule";

export class RuleService {
    private static rules: Array<ScoringRule> = [];
    private static storageKey = 'chengzheng_scoring_rules';

    /**
     * 初始化规则服务
     * 从本地存储加载规则数据
     */
    static initialize(): void {
        this.loadFromStorage();
    }

    /**
     * 获取所有计分规则
     * @returns 计分规则列表
     */
    static getAllRules(): Array<ScoringRule> {
        return this.rules;
    }

    /**
     * 根据ID查找计分规则
     * @param id 规则ID
     * @returns 找到的规则或undefined
     */
    static getRuleById(id: number): ScoringRule | undefined {
        return this.rules.find(rule => rule.id === id);
    }

    /**
     * 加载规则数据从本地存储
     */
    private static loadFromStorage(): void {
        const data = localStorage.getItem(this.storageKey);
        if (data) {
            const parsed = JSON.parse(data);
            this.rules = parsed.map((r: any) => {
                let rule = new ScoringRule(r.category, r.item, r.description, r.rules)
                Object.assign(rule, r);
                rule.id = r.id; // 保持原有ID
                return rule;
            });
        } else {
            // 如果没有存储数据，初始化为空数组
            this.rules = [];
        }
    }

    /**
     * 保存规则数据到本地存储
     */
    private static saveToStorage(): void {
        localStorage.setItem(this.storageKey, JSON.stringify(this.rules));
    }

    /**
     * 添加或更新计分规则
     */
    static saveRule(rule: ScoringRule): void {
        const index = this.rules.findIndex(r => r.id === rule.id);
        if (index !== -1) {
            this.rules[index] = rule; // 更新现有规则
        } else {
            this.rules.push(rule); // 添加新规则
        }
        this.saveToStorage();

    }

    /**
     * 删除计分规则
     */
    static deleteRule(id: number): boolean {
        const index = this.rules.findIndex(r => r.id === id);
        if (index !== -1) {
            this.rules.splice(index, 1);
            this.saveToStorage();
            return true;
        }
        return false;
    }
}